package com.zzyl.framework.interceptor;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @version 1.0
 * @description 说明
 * @package com.zzyl.framework.interceptor
 */
@Component
@Slf4j
public class MemberInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求头中的token
        String token = request.getHeader("authorization");
        //2.token是否为空
        if(StrUtil.isNotEmpty(token)) {
            //3.不为则解析token
            Claims claims = tokenService.parseToken(token);
            if(CollUtil.isNotEmpty(claims)) {
                //4.解析成功，得到载荷
                Long userId = claims.get("userId", Long.class);
                //  得到登录用户信息,获得登录用户的id
                //  把登录用户id设置ThreadLocal里
                UserThreadLocal.set(userId);
                return true;
            }
        }
        // 无token或token解析失败，响应401让用户重新登录
        response.setStatus(HttpStatus.UNAUTHORIZED);
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
